import { Breadcrumb, Button, Card, Dropdown, Table, Menu, Modal, Upload, Form, Input, message } from 'antd';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import genduo from '@assets/genduo.svg';
import styles from './style.less';
import * as action from './store/action';
import moment from 'moment';
import nProgress from 'nprogress'; // 引入请求进度条插件
import 'nprogress/nprogress.css'; // 请求进度条css样式
import { DownloadMenu, RenameMenu, DeleteMenu } from './component/menu';
import * as Icon from '@ant-design/icons';

class index extends Component {

  constructor(props) {
    super(props);
    this.state = {
      addFolderVisible: false,
      modifyFolderVisible: false,
      selectBreadcrumb: [{
        folderId: 0,  // 当前文件目录id
        folderName: '个人文件'
      }],
      folderId: 0,  // 当前文件目录id
      modifyFolderId: 0 // 修改的文件夹路径
    }
  }

  componentDidMount() {
    this.props.getRootFolder();
    console.log("222222",this.props.getRootFolder());
  }

  render() {

    const { addFolderVisible, folderId, selectBreadcrumb, modifyFolderVisible, modifyFolderId } = this.state;

    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        render: (text, record) => {
          /**
           * 图标内容 key(文件类型)-value(文件图标)
           * 添加图标需要加上对应的key-value对
           */
          const iconType = {
            'folder': "FolderOpenOutlined",
            'file': "FileOutlined"
          }
          return (
            <div style={{ display: 'flex', height: 'inherit', justifyContent: 'flex-start' }} onClick={() => {tableHandle('load', record)}}>
              <a className='fName'>
                {React.createElement(Icon[iconType[record.type]], { style: { fontSize: '18px' } })}&emsp;
                <span>{text}</span>
              </a>
            </div>
          )
        }
      },
      {
        title: '最后修改时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        width: 400,
        render: (text) => {
          return moment(text).format("yyyy-MM-DD HH:mm:ss");
        }
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 300,
        render: (text) => {
          switch (text) {
            case 'folder': {
              return "文件夹"
            }
            case 'file': {
              return "文件"
            }
          }
        }
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        key: 'createBy',
        width: 150
      },
      {
        title: '操作',
        align: 'center',
        width: 50,
        render: (text) => {
          const menu = () => {
            switch (text.type) {
              // 文件夹菜单
              case 'folder': {
                return (
                  <Menu>
                    <RenameMenu tableHandle={tableHandle} text={text} />
                    <DeleteMenu tableHandle={tableHandle} text={text} />
                  </Menu>
                )
              }
              // 文件菜单
              case 'file': {
                return (
                  <Menu>
                    <DownloadMenu tableHandle={tableHandle} text={text} />
                    <DeleteMenu tableHandle={tableHandle} text={text} />
                  </Menu>
                )
              }
            }
          }
          return (
            <Dropdown overlay={menu} trigger={['click']}>
              <img style={{ width: '80px', height: '20px', cursor: 'pointer', zIndex: 10086 }} src={genduo} />
            </Dropdown>
          )
        }
      }
    ]

    // 新建文件夹
    const addFolder = (value) => {
      var data = {
        folderId: folderId,
        folderName: value.folderName
      }
      this.props.addFolder(data)
      this.setState({
        addFolderVisible: false
      })
    }

    // 修改文件夹
    const modifyFolder = (value) => {
      var data = {
        folderId: modifyFolderId,
        parentFolderId: folderId,
        folderName: value.folderName
      }
      this.props.modifyFolder(data)
      this.setState({
        modifyFolderVisible: false
      })
    }

    /**
     * table处理
     * @param {string} key 
     * @param {JSONobject} record 
     */
    const tableHandle = (key, record) => {
      const this_ = this;
      switch (key) {
        // 加载子文件
        case 'load': {
          if (record.type === 'folder') {
            this.setState({
              folderId: record.id
            })
            this.props.listFolderAndFile(record.id)

            // 面包屑添加路径
            var arr = selectBreadcrumb;
            arr.push({
              folderId: record.id,
              folderName: record.name
            })
            this.setState({
              selectBreadcrumb: arr
            })
          }
          break;
        }
        // 删除文件夹
        case 'delete': {
          Modal.confirm({
            title: `是否删除${record.name}？`,
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
              switch (record.type) {
                // 文件类型：文件夹
                case 'folder': {
                  console.log("11111",folderId);
                  this_.props.deleteFolder({
                    folderId: record.id,
                    parentFolderId: folderId
                  });
                  break;
                }
                case 'file': {
                  this_.props.deleteFile({
                    fileId: record.id,
                    parentFolderId: folderId
                  })
                }
              }
            }
          });
          break;
        }
        // 重命名
        case 'rename': {
          this_.setState({
            modifyFolderVisible: true,
            modifyFolderId: record.id
          })
          break;
        }
        case 'download': {
          // 这里不直接用window.location.href 是因为浏览器会直接打开pdf而不会下载
          var link = document.createElement('a');
          link.href = '/api/server' + record.path
          link.download = record.name;
          link.click()
          link.remove();
          break;
        }
      }

    }

    // 面包屑点击回调函数
    const breadcrumbClick = (folderId) => {
      if (folderId === 0) {
        this.props.getRootFolder()
      } else {
        this.props.listFolderAndFile(folderId);
      }

      // 删除选中的元素后几位
      var arr = selectBreadcrumb;
      arr.map((item, index) => {
        if (item.folderId === folderId) {
          arr.splice(index + 1);
        }
      })
      this.setState({
        selectBreadcrumb: arr,
        folderId: folderId
      })
    }

    // 上传文件请求
    const uploadFileRequest = ({ file }) => {
      if (file.status === 'done') {
        if (file.response !== undefined) {
          if (file.response.response.res) {
            message.success('上传成功');
            if (folderId !== 0) {
              this.props.listFolderAndFile(folderId)
            } else {
              // 获取文件根目录文件
              this.props.getRootFolder()
            }
          } else {
            message.error(file.response.response.exception);
          }
        }
        nProgress.done();
      } else if (file.status === 'uploading') {
        nProgress.start();
        nProgress.set(0.5);
      } else {
        message.error('excle上传失败, 请重新上传', 1);
        nProgress.done();
        return;
      }
    }

    // 上传文件
    const uploadFile = {
      name: 'file',
      // accept: '',
      showUploadList: false,
      action: '/api/server/web/rest/DocumentRest/uploadFile',
      data: { folderId: folderId },
      onChange: uploadFileRequest,
    };

    return (
      <Card
        title="个人文件"
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '5px' }}>
          <Breadcrumb >
            {
              selectBreadcrumb.map((item, index) => {
                return <Breadcrumb.Item key={index} onClick={() => breadcrumbClick(item.folderId)}><a>{item.folderName}</a></Breadcrumb.Item>
              })
            }
          </Breadcrumb>
          <div>
            <Button type='primary' style={{ marginRight: '10px' }} onClick={() => { this.setState({ addFolderVisible: true }) }}>新建文件夹</Button>
            {
              folderId === 0 ? null : <Upload {...uploadFile} ><Button type='primary'>上传文件</Button></Upload>
            }
          </div>
        </div>
        <Table
          className={styles.personal_table}
          columns={columns}
          dataSource={this.props.data}
          // onRow={record => {
          //   return {
          //     onClick: event => { tableHandle('load', record) }, // 点击行
          //   }
          // }}
        />

        {/* 添加文件夹弹窗 */}
        <Modal
          title="添加文件夹"
          visible={addFolderVisible}
          onCancel={() => {
            this.setState({
              addFolderVisible: false
            })
          }}
          footer={null}
          destroyOnClose
        >
          <Form onFinish={addFolder}>
            <Form.Item label="文件夹名称" name="folderName" rules={[{ required: true, message: "请输入文件夹名称" }]}>
              <Input></Input>
            </Form.Item>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <Button type='primary' htmlType='submit' style={{ marginRight: '10px' }}>确认</Button>
              <Button onClick={() => this.setState({ addFolderVisible: false })}>取消</Button>
            </div>
          </Form>
        </Modal>

        {/* 修改文件夹弹窗 */}
        <Modal
          title="修改文件夹"
          visible={modifyFolderVisible}
          onCancel={() => {
            this.setState({
              modifyFolderVisible: false
            })
          }}
          footer={null}
          destroyOnClose
        >
          <Form onFinish={modifyFolder}>
            <Form.Item label="文件夹名称" name="folderName" rules={[{ required: true, message: "请输入文件夹名称" }]}>
              <Input></Input>
            </Form.Item>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <Button type='primary' htmlType='submit' style={{ marginRight: '10px' }}>确认</Button>
              <Button onClick={() => this.setState({ modifyFolderVisible: false })}>取消</Button>
            </div>
          </Form>
        </Modal>
      </Card>
    )
  }
}

const mapStateToProps = (state) => ({
  data: state.personalFile.data
})

const mapDispatchToProps = (dispatch) => ({
  getRootFolder() {
    dispatch(action.getRootFolder())
  },
  addFolder(data) {
    dispatch(action.addFolder(data))
  },
  deleteFolder(data) {
    dispatch(action.deleteFolder(data))
  },
  listFolderAndFile(data) {
    dispatch(action.listFolderAndFile(data))
  },
  deleteFile(data) {
    dispatch(action.deleteFile(data))
  },
  modifyFolder(data) {
    dispatch(action.modifyFolder(data))
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(index)